<template>
  <el-dialog
    v-model="visible"
    :title="title"
    :width="width"
    class="tech-dialog"
    @close="handleClose"
  >
    <el-form 
      :model="formData" 
      :rules="rules" 
      ref="formRef" 
      :label-width="labelWidth" 
      class="tech-form"
    >
      <slot name="form-content"></slot>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel" class="tech-button">
          {{ cancelText }}
        </el-button>
        <el-button 
          type="primary" 
          @click="handleConfirm" 
          :loading="loading" 
          class="tech-button"
        >
          <i v-if="confirmIcon" :class="confirmIcon"></i>
          {{ confirmText }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'

interface Props {
  modelValue: boolean
  title: string
  formData: Record<string, any>
  rules?: Record<string, any>
  loading?: boolean
  width?: string
  labelWidth?: string
  confirmText?: string
  cancelText?: string
  confirmIcon?: string
}

const props = withDefaults(defineProps<Props>(), {
  loading: false,
  width: '600px',
  labelWidth: '100px',
  confirmText: '确定',
  cancelText: '取消',
  confirmIcon: 'fa fa-save'
})

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'confirm': []
  'cancel': []
  'close': []
}>()

const visible = ref(props.modelValue)
const formRef = ref()

watch(() => props.modelValue, (newVal) => {
  visible.value = newVal
})

watch(visible, (newVal) => {
  emit('update:modelValue', newVal)
})

const handleClose = () => {
  emit('close')
}

const handleCancel = () => {
  visible.value = false
  emit('cancel')
}

const handleConfirm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    emit('confirm')
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 暴露表单引用给父组件
defineExpose({
  formRef,
  validate: () => formRef.value?.validate(),
  clearValidate: () => formRef.value?.clearValidate(),
  resetFields: () => formRef.value?.resetFields()
})
</script>

<style lang="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
